//
//  ThemeViewController.m
//  leo
//
//  Created by 常艳 on 15/9/19.
//  Copyright (c) 2015年 mdx. All rights reserved.
//

#import "ThemeViewController.h"
#import "ThemeCollectionViewCell.h"
#import "ChooseThemeViewController.h"
#import "Theme.h"
#import "LeoMsg.h"
#import "ThemeLock.h"
#import "User.h"
#import "DataManager.h"
#import "GrowDataManager.h"
#import "Growth.h"
#import "AppDelegate.h"
#import "SyncManager.h"
@interface ThemeViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
@property(nonatomic,retain) NSArray *lockData;
@property(nonatomic,retain) Theme *theme;
@property(nonatomic,strong)  Watch *selectWatch;
@property(nonatomic,strong) DataManager *dataManager;
@property(nonatomic,strong) GrowDataManager *growDataManager;
@property(nonatomic,assign) int nowLevel;
@property(nonatomic,assign) float rate;
@property(nonatomic,strong) ThemeCollectionViewCell *selectCell;
@property(nonatomic,strong) ThemeCollectionViewCell *currentCell;
@property(nonatomic,strong) ThemeLock *selectLock;
@end

@implementation ThemeViewController
@synthesize lockData;
@synthesize theme;
@synthesize selectWatch;
@synthesize dataManager;
@synthesize growDataManager;
@synthesize nowLevel;
@synthesize rate;
@synthesize selectCell;
@synthesize currentCell;
@synthesize selectLock;
-(void)dealloc
{
    lockData=NULL;
    theme=NULL;
    selectWatch=NULL;
    dataManager=NULL;
    growDataManager=NULL;
    selectCell=NULL;
    currentCell=NULL;
    selectLock=NULL;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.extendedLayoutIncludesOpaqueBars=YES;
    rate=[[UIScreen mainScreen] bounds].size.width/320;
    self.title=@"成长主题";
    UIBarButtonItem *rightButton=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"theme_choose_icon@2x.png"] style:UIBarButtonItemStyleDone target:self action:@selector(chooseTheme)];
    [self.navigationItem setRightBarButtonItem:rightButton];
    rightButton=NULL;
    
    [self.collectionView registerClass:[ThemeCollectionViewCell class] forCellWithReuseIdentifier:@"ThemeCollectionViewCell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"ThemeCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"ThemeCollectionViewCell"];
    self.collectionView.scrollEnabled=YES;
    // Do any additional setup after loading the view from its nib.
    //从数据库中读取当前的主题
    [self initDataProxy];
    [self initLevelData];
    [self initThemeUi];
    [self initLevel];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [self initLevelData];
    [self initThemeUi];
    [self initLevel];
    [self.collectionView reloadData];
}
-(void)initDataProxy
{
    dataManager=[[DataManager alloc] init];
    growDataManager=[[GrowDataManager alloc] init];
}

-(void)initLevelData
{
    User *user=[User sharedSingleton];
    if(user==NULL)
        return;
    if(dataManager==NULL||growDataManager==NULL)
        return;
    selectWatch=[dataManager getActiveWatch:user.uid];
    if(selectWatch==NULL)
        return;
    lockData=[growDataManager getThemeLocks:selectWatch.themeId];
    
}
-(void)initThemeUi
{
    if(selectWatch==NULL||growDataManager==NULL)
        return;
    theme=[growDataManager getThemeInfo:selectWatch.themeId];
    if(theme==NULL)
        return;
    self.headImg.image=[UIImage imageNamed:theme.themePicUrl];
    self.lableImg.image=[UIImage imageNamed:theme.labPicUrl];
    self.titleLable.text=theme.name;
    
}
-(void)initLevel
{
    if(growDataManager==NULL||selectWatch==NULL)
        return;
    Growth *growth=[growDataManager getLatestGrowth:selectWatch.deviceUid];
    nowLevel=[Tooler getLevelNum:growth.semp];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if(lockData!=NULL)
        return lockData.count;
    else
        return 0;
    
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * CellIdentifier = @"ThemeCollectionViewCell";
    ThemeCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    if(cell==NULL)
    {
        NSLog(@"%@,cellForItemAtIndexPath,cell is null.",theme_tag);
        return cell;
    }
    else
    {
        ThemeLock *lock=[lockData objectAtIndex:[indexPath row]];
        if(lock==NULL)
        {
           NSLog(@"%@,cellForItemAtIndexPath,level is null.",theme_tag);
            return cell;
        }
        UIImage *levelImg;

        if (lock.level <= nowLevel) {
             cell.levelLable.text = @"未使用";
        }
        else
        {
            cell.levelLable.text = [NSString stringWithFormat:@"%ld级解锁",indexPath.item * 5];
            if (indexPath.item == 0) {
            cell.levelLable.text = @"1级解锁";
            }
        }
        
        levelImg=[UIImage imageNamed:lock.unlocPicUrl];
        if (lock.level == selectWatch.watchTheme) {
            levelImg=[UIImage imageNamed:lock.lockPicUrl];
            cell.levelLable.text = @"使用中";
        }
           cell.levelImg.image = levelImg;

        levelImg = NULL;
    }
    
    return cell;
}
#pragma mark --UICollectionViewDelegateFlowLayout
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //CGRect rect=[[UIScreen mainScreen] bounds];
    //CGSize size=rect.size;
    //float width=(size.width*rate-150*rate)/2;
    float width=100*rate;
    float height=width*1.3;
    return CGSizeMake(width, height);
}
//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5*rate, 0, 5*rate, 0);
}
#pragma mark --UICollectionViewDelegate
//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    AppDelegate *mydelegate=[[UIApplication sharedApplication] delegate];
    if(mydelegate!=NULL)
    {
        if(mydelegate.isAdmin==NO)
            return;
    }
    ThemeLock *lock=[lockData objectAtIndex:[indexPath row]];
    selectLock=lock;
    if(lock==NULL)
        return;
    if(lock.level>nowLevel)
        return;
    ThemeCollectionViewCell * cell = (ThemeCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    if(selectCell==cell)
        return;
    currentCell=cell;
    [self showAlert];
   
}

//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
-(void)showAlert
{
    NSString *title=@"是否切换成长中心表盘？";
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                    message:title
                                                   delegate:self
                                          cancelButtonTitle:@"否"
                                          otherButtonTitles:@"是",nil];
    [alert show];
    alert=nil;
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if(buttonIndex==1)
    {
        SyncManager *syncManager=[[SyncManager alloc] init];
        if(syncManager==NULL||dataManager==NULL||selectWatch==NULL)
        {
            [LeoMsg showToastMsg:@"设置表盘发生错误" parentView:self.navigationController.view showPosition:TOAST_SHOW_END hideAfterDelay:1];
            return;
        }
        NSString *watchParams=[NSString stringWithFormat:@"{\"themeId\":%@,\"wpLevel\":%d}",selectWatch.themeId,selectLock.level];
        [syncManager sendCommand:selectWatch.deviceUid type:THEME_CHANGE watchParams:watchParams completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
            if(result==SUCESS)
            {
                BOOL result=[dataManager setWatchTheme:selectLock.level deviceUid:selectWatch.deviceUid];
                if(result)
                {

                    selectCell=currentCell;
                    [self initLevelData];
                    [self.collectionView reloadData];
                }
            }
            else
            {
                [Tooler showHttpToast:result description:description msg:@"设置表盘失败" parentView:self.navigationController.view showPosition:TOAST_SHOW_END hideAfterDelay:1];
            }
        }];

    }
}
-(void)chooseTheme
{
    ChooseThemeViewController *chooseViewController=[[ChooseThemeViewController alloc]init];
    [self.navigationController pushViewController:chooseViewController animated:YES];
}
@end
